#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基于事件系统的智能回复插件
"""

import random
from typing import Dict, Optional, Any
from common.logger import logger
from plugins.base_plugin import BasePlugin
from plugins.event_system import Event, EventType, on_message, on_any_message, middleware


class Plugin(BasePlugin):
    """基于事件系统的智能回复插件类"""
    
    def __init__(self, config: Dict[str, Any], event_bus):
        super().__init__(config, event_bus)
        self.keywords = self.settings.get("keywords", {})
        self.default_reply = self.settings.get("default_reply", "抱歉，我不太理解您的意思。您可以发送'帮助'查看我能做什么。")
    
    @on_message(EventType.MESSAGE_TEXT)
    async def handle_text_message(self, event: Event) -> Optional[Dict[str, Any]]:
        """处理文本消息事件"""
        try:
            # 检查插件是否启用
            if not self.is_enabled():
                return None
            
            data = event.data
            content = data.get("content", "")
            sender_wxid = data.get("sender_wxid", "")
            
            # 查找匹配的关键词
            reply = self._find_reply(content)
            
            if reply:
                logger.info(f"智能回复插件处理消息: {sender_wxid} -> {content} -> {reply}")
                
                return self.create_text_response(reply)
            
            return None
            
        except Exception as e:
            logger.error(f"智能回复插件处理消息失败: {e}")
            return None
    
    def _find_reply(self, content: str) -> Optional[str]:
        """查找匹配的回复"""
        try:
            # 遍历关键词
            for keyword, replies in self.keywords.items():
                if keyword in content:
                    # 随机选择一个回复
                    if isinstance(replies, list) and replies:
                        return random.choice(replies)
                    elif isinstance(replies, str):
                        return replies
            
            # 如果没有匹配的关键词，返回默认回复
            return self.default_reply
            
        except Exception as e:
            logger.error(f"查找回复失败: {e}")
            return None 